/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Client.network;

import Client.domain.ClientDomainController;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 *
 * @author Ripper
 */
public class NetworkClient implements Runnable 
{
    private InetAddress host;
    private int PORT;
    private String ip;
    
    private String[] initmessage;
    private ClientDomainController cdc;
    
    private boolean isRunning = true;
    
    private String inputMessage = "";
    private String outputMessage = "";
    
    private BufferedReader in;
    private PrintWriter out;
    
    public NetworkClient(String ipAdd, int prt, ClientDomainController clDoCo,
            String[] initialMessage) throws UnknownHostException
    {
        PORT = prt;
        ip = ipAdd;
        
        host = InetAddress.getByName(ip);
        initmessage = initialMessage;
        cdc = clDoCo;
    }
    
    @Override
    public void run()
    {
        if(isRunning)
        {
            Socket link = null;	
            
            try
            {
                link = new Socket(host,PORT);
                
                in = new BufferedReader(new InputStreamReader(link.getInputStream()));
                out = new PrintWriter(link.getOutputStream(),true);
                
                String message = "", response = "";
                
                out.println("#CLN:HELLO!NEW_USR#");
                out.flush();

                boolean go_on = true;
                response = in.readLine();
                try
                {
                    if(!response.equals("#SRV:HELLO_NEW_USR#"))
                    {
                        throw new Exception();
                    }
                    if(initmessage.length == 2)
                    {
                        out.println("#CLN:LOGIN:USR=\""+initmessage[0]+"\";PWD=\""+initmessage[1]+"\"#");
                        out.flush();

                        response = in.readLine();
                        if(response.startsWith("#SRV:LOGIN_OK:"))
                        {
                            String userName = response.substring(response.lastIndexOf(':')+1);
                            cdc.loginOk(userName);
                        }
                        else if(response.equals("#SRV:WRONG_PASSWORD#"))
                        {
                            cdc.loginWrongPassword();
                            go_on = false;
                        }
                        else if(response.equals("#SRV:UNKOWN_USER#"))
                        {
                            cdc.loginUnkownUser();
                            go_on = false;
                        }
                        else if(response.equals("#SRV:ALREADY_LOGGED_IN#"))
                        {
                            cdc.alreadyLoggedIn();
                            go_on = false;
                        }
                        else
                        {
                            throw new Exception();
                        }
                    }
                    else
                    {
                        String data = "";
                        for(String i: initmessage)
                        {
                            data += i+ ";";
                        }

                        //register
                        out.println("#CLN:REGISTER:"+data+"#");
                        out.flush();

                        response = in.readLine();
                        if(response.startsWith("#SRV:REGISTER_OK:"))
                        {
                            String userName = response.substring(response.lastIndexOf(':')+1);
                            cdc.registerOk(userName);
                        }
                        else if(response.equals("#SRV:USERNAME_TAKEN#"))
                        {
                            cdc.registrationFailed("Username is already taken.");
                            go_on = false;
                        }
                        else if(response.equals("#SRV:EMAIL_TAKEN#"))
                        {
                            cdc.registrationFailed("Email address is already assigned to a user.");
                            go_on = false;
                        }
                        else
                        {
                            throw new Exception();
                        }
                    }
                }
                catch(Exception ex)
                {
                    if(!message.equals("#SRV:CLOSE_CONNECTION#"))
                    {
                        System.err.println("Unexpected response from server:\nresponse = "+response);
                        message = "#SRV:CLOSE_CONNECTION#";
                    }
                }
                
                /*while (!message.equals("#SRV:CLOSE_CONNECTION#") && go_on)
                {
                    if(outputMessage.length() > 0 && inputMessage.length() == 0)
                    {
                        out.println(outputMessage);
                        out.flush();
                        
                        inputMessage = in.readLine();
                        outputMessage = "";
                    }
                    else
                    {
                        try
                        {
                            Thread.sleep(1);
                        }
                        catch(Exception ex)
                        {
                            
                        }
                    }
                }*/
                while(isRunning && go_on)
                {
                    try
                    {
                        Thread.sleep(1);
                    }
                    catch(Exception ex)
                    {
                        
                    }
                }

                
                if(message.equals("#SRV:CLOSE_CONNECTION#"))
                {
                    System.err.println("server is closing connection.");
                }
            }
            catch(Exception ex)
            {
                cdc.displayErrorMessage("Connection Error: \n\n"+ex.toString());
            }
            finally
            {
                try
                {
                    link.close();
                }
                catch(Exception ex)
                {
                    
                }
            }
        }
        
    }
    
    public void stopRunning()
    {
        isRunning = false;
        try
        {
            out.println("#CLN:CLOSE_CONNECTION#");
            out.flush();
        }
        catch(Exception ex)
        {
            
        }
    }
    
    public String extractInputMessage()
    {
        String s = inputMessage;
        inputMessage = "";
        return s;
    }

    public String getInputMessage() {
        return inputMessage;
    }

    public void setInputMessage(String inputMessage) {
        this.inputMessage = inputMessage;
    }

    public String getOutputMessage() {
        return outputMessage;
    }

    public void setOutputMessage(String outputMessage) {
        this.outputMessage = outputMessage;
    }
    
    public String directlyAskServer(String question) throws IOException
    {
        out.println(question);
        out.flush();

        return in.readLine();
    }
}
